const db = require('../config/db');
const { sendError } = require('../utils/response');

module.exports = {
  // 添加地址
  async addAddress(userId, addressData) {
    const { receiver_name, receiver_phone, province, city, district, detail_address, is_default } = addressData;
    
    const conn = await db.getConnection();
    try {
      await conn.beginTransaction();
      
      // 如果设置为默认地址，先取消其他默认地址
      if (is_default) {
        await conn.execute(
          'UPDATE addresses SET is_default = 0 WHERE user_id = ?',
          [userId]
        );
      }
      
      // 添加新地址
      const [result] = await conn.execute(
        'INSERT INTO addresses (user_id, receiver_name, receiver_phone, province, city, district, detail_address, is_default) ' +
        'VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
        [userId, receiver_name, receiver_phone, province, city, district, detail_address, is_default || 0]
      );
      
      await conn.commit();
      return result.insertId;
    } catch (err) {
      await conn.rollback();
      throw err;
    } finally {
      conn.release();
    }
  },

  // 更新地址
  async updateAddress(userId, addressId, addressData) {
    const { receiver_name, receiver_phone, province, city, district, detail_address, is_default } = addressData;
    
    const conn = await db.getConnection();
    try {
      await conn.beginTransaction();
      
      // 如果设置为默认地址，先取消其他默认地址
      if (is_default) {
        await conn.execute(
          'UPDATE addresses SET is_default = 0 WHERE user_id = ? AND id != ?',
          [userId, addressId]
        );
      }
      
      // 更新地址
      const [result] = await conn.execute(
        'UPDATE addresses SET receiver_name = ?, receiver_phone = ?, province = ?, city = ?, ' +
        'district = ?, detail_address = ?, is_default = ? WHERE id = ? AND user_id = ?',
        [receiver_name, receiver_phone, province, city, district, detail_address, is_default || 0, addressId, userId]
      );
      
      if (result.affectedRows === 0) {
        throw new Error('地址不存在或无权修改');
      }
      
      await conn.commit();
      return true;
    } catch (err) {
      await conn.rollback();
      throw err;
    } finally {
      conn.release();
    }
  },

  // 删除地址
  async deleteAddress(userId, addressId) {
    const [result] = await db.execute(
      'DELETE FROM addresses WHERE id = ? AND user_id = ?',
      [addressId, userId]
    );
    
    if (result.affectedRows === 0) {
      throw new Error('地址不存在或无权删除');
    }
    
    return true;
  },

  // 获取用户地址列表
  async getUserAddresses(userId) {
    console.log("userId"+userId);
    
    const [addresses] = await db.execute(
      'SELECT * FROM addresses WHERE user_id = ? ORDER BY is_default DESC, created_at DESC',
      [userId]
    );
    return addresses;
  },

  // 获取地址详情
  async getAddressById(userId, addressId) {
    const [addresses] = await db.execute(
      'SELECT * FROM addresses WHERE id = ? AND user_id = ?',
      [addressId, userId]
    );
    
    if (addresses.length === 0) {
      throw new Error('地址不存在');
    }
    
    return addresses[0];
  },
  // 获取默认地址
  async getDefaultAddress(userId) {
    const [addresses] = await db.execute(
      'SELECT * FROM addresses WHERE  user_id = ? and  is_default = 1',
      [userId]
    );
    
    if (addresses.length === 0) {
      throw new Error('地址不存在');
    }
    
    return addresses[0];
  },

  // 设置默认地址
  async setDefaultAddress(userId, addressId) {
    const conn = await db.getConnection();
    try {
      await conn.beginTransaction();
      
      // 取消当前默认地址
      await conn.execute(
        'UPDATE addresses SET is_default = 0 WHERE user_id = ?',
        [userId]
      );
      
      // 设置新默认地址
      const [result] = await conn.execute(
        'UPDATE addresses SET is_default = 1 WHERE id = ? AND user_id = ?',
        [addressId, userId]
      );
      
      if (result.affectedRows === 0) {
        throw new Error('地址不存在或无权修改');
      }
      
      await conn.commit();
      return true;
    } catch (err) {
      await conn.rollback();
      throw err;
    } finally {
      conn.release();
    }
  }
};